<template>
  <div class="menu-container">
    <div class="header">
      <div class="search-area">
        <el-input v-model="input" placeholder="请输入菜品名称" @keyup.enter.native="handleSearch">
          <i
            slot="prefix"
            class="el-input__icon el-icon-search"
            @click="handleSearch"
          />
        </el-input>
      </div>
      <div class="action-area">
        <div class="batch-actions">
          <el-link :underline="false" @click="handleBatchDelete">批量删除</el-link>
          <el-divider direction="vertical" />
          <el-link :underline="false" @click="handleBatchStatus(0)">批量停售</el-link>
          <el-divider direction="vertical" />
          <el-link :underline="false" @click="handleBatchStatus(1)">批量启售</el-link>
        </div>
        <el-button type="primary" class="add-btn" @click="handleAdd">
          <i class="el-icon-plus"> 新建菜品 </i>
        </el-button>
      </div>
    </div>
    <div>
      <div class="table-wrapper">
        <div class="table-container">
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            :header-cell-style="headerCellStyle"
            :cell-style="cellStyle"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="45" />
            <el-table-column prop="name" label="菜品名称" width="130" />
            <el-table-column prop="image" label="图片" width="130">
              <template slot-scope="scope">
                <el-image
                  v-if="scope.row.image"
                  style="width: 60px; height: 60px; border-radius: 4px;"
                  :src="getImageUrl(scope.row.image)"
                  :preview-src-list="[getImageUrl(scope.row.image)]"
                  fit="cover"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline" style="font-size: 20px; color: #909399;" />
                  </div>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="categoryName" label="菜品分类" width="150" />
            <el-table-column prop="price" label="售价" width="150" />
            <el-table-column prop="status" label="售卖状态" width="120">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
                  {{ scope.row.status === 1 ? "启售" : "停售" }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="最后操作时间" width="235" />
            <el-table-column prop="action" label="操作" width="240">
              <template slot-scope="scope">
                <el-link :underline="false" @click="handleEdit(scope.row)">修改</el-link>
                <el-divider direction="vertical" />
                <el-link
                  :underline="false"
                  :style="{ color: scope.row.status === 1 ? '#f56c6c' : '#67c23a' }"
                  @click="handleStatusChange(scope.row)"
                >{{ scope.row.status === 1 ? '停售' : '启售' }}</el-link>
                <el-divider direction="vertical" />
                <el-link
                  :underline="false"
                  style="color: #f56c6c;"
                  @click="handleDelete(scope.row)"
                >删除</el-link>
              </template>
            </el-table-column>
          </el-table>
          <Pagination
            v-show="total>0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
            @pagination="getList"
          />
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getCategoryList, updateDishStatus, deleteDish } from '@/api/menu'
import Pagination from '@/components/Pagination'
import { debounce } from 'lodash'

export default {
  name: 'MenuManagement',
  components: {
    Pagination
  },
  data() {
    return {
      input: '',
      tableData: [], // 表格数据
      loading: false, // 加载状态
      total: 0,
      imageBaseUrl: process.env.VUE_APP_BASE_API || '',
      selectedRows: [], // 选中的行
      // 分页参数
      listQuery: {
        page: 1,
        limit: 10
      }
    }
  },
  created() {
    // 创建防抖搜索函数
    this.debouncedSearch = debounce(this.getList, 500)
  },
  mounted() {
    this.getList()
  },
  methods: {
    getImageUrl(imageName) {
      if (!imageName) return ''
      // 如果已经是完整URL，直接返回
      if (imageName.startsWith('http')) {
        return imageName
      }
      return `${this.imageBaseUrl}/common/download?name=${imageName}`
    },
    // 表头样式
    headerCellStyle() {
      return {
        'background-color': '#f5f7fa',
        color: '#606266',
        'font-weight': '500',
        'border-bottom': '1px solid #e4e7ed',
        padding: '12px 0',
        'text-align': 'center'
      }
    },
    // 单元格样式
    cellStyle() {
      return {
        'border-bottom': '1px solid #e4e7ed',
        padding: '12px 0',
        'text-align': 'center'
      }
    },
    handleSearch() {
      this.listQuery.page = 1 // 搜索时重置到第一页
      this.debouncedSearch()
    },
    getList() {
      this.loading = true
      const params = {
        page: this.listQuery.page,
        pageSize: this.listQuery.limit
      }

      if (this.input) {
        params.name = this.input
      }

      getCategoryList(params)
        .then((response) => {
          if (response.data && response.data.records) {
            this.tableData = response.data.records
            this.total = response.data.total || 0
          } else {
            this.tableData = []
            this.total = 0
          }
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    handleAdd() {
      this.$router.push('/menu/form')
    },
    handleEdit(row) {
      this.$router.push(`/menu/form?id=${row.id}`)
    },
    // 单个菜品状态修改
    handleStatusChange(row) {
      const newStatus = row.status === 1 ? 0 : 1
      const action = newStatus === 1 ? '启售' : '停售'

      this.$confirm(`确定要${action}该菜品吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await updateDishStatus(row.id, newStatus)
          this.$message.success(`${action}成功`)
          this.getList() // 重新加载数据
        } catch (error) {
          console.error(`${action}失败:`, error)
          this.$message.error(`${action}失败`)
        }
      })
    },
    // 单个删除
    handleDelete(row) {
      this.$confirm('确定要删除该菜品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await deleteDish(row.id)
          this.$message.success('删除成功')
          this.getList() // 重新加载数据
        } catch (error) {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      })
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection
    },
    // 批量状态修改
    handleBatchStatus(status) {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要操作的菜品')
        return
      }

      const action = status === 1 ? '启售' : '停售'
      const ids = this.selectedRows.map(item => item.id).join(',')

      this.$confirm(`确定要${action}选中的${this.selectedRows.length}个菜品吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          await updateDishStatus(ids, status)
          this.$message.success(`批量${action}成功`)
          this.getList() // 重新加载数据
          this.selectedRows = [] // 清空选择
        } catch (error) {
          console.error(`批量${action}失败:`, error)
          this.$message.error(`批量${action}失败`)
        }
      })
    },
    // 批量删除
    handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要删除的菜品')
        return
      }

      this.$confirm(`确定要删除选中的${this.selectedRows.length}个菜品吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        try {
          const ids = this.selectedRows.map(item => item.id).join(',')
          await deleteDish(ids)
          this.$message.success('批量删除成功')
          this.getList() // 重新加载数据
          this.selectedRows = [] // 清空选择
        } catch (error) {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        }
      })
    }
  }
}
</script>
<style scoped>
.pagination-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
}
.menu-container {
  padding: 20px;
  background: #fff;
  min-height: calc(100vh - 84px);
  width: 100%;
  box-sizing: border-box;
}
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e4e7ed;
    width: 100%;

    .search-area {
        display: flex;
        align-items: center;
        margin-left: 10px;
        margin-top: 15px;
    }

    .action-area {
        display: flex;
        align-items: center;
        margin-right: 5px;
        margin-top: 15px;

        .batch-actions {
            display: flex;
            align-items: center;
            margin-right: 20px;
        }
    }
}
.table-wrapper {
  width: 100%;
  display: flex;
  justify-content: center;
}

.table-container {
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  width: 100%;
  max-width: 1200px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  ::v-deep .el-table {
    border: none;
    width: 100% !important;

    th {
      background-color: #f5f7fa !important;
    }

    td,
    th {
      border-bottom: 1px solid #e4e7ed;
    }

    &::before {
      display: none;
    }

    .el-table__body-wrapper,
    .el-table__header-wrapper {
      width: 100% !important;
    }
  }
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  border-radius: 4px;
  color: #909399;
}
</style>
